package org.jdns.jfreechess.draw;

import java.util.List;
import java.util.Map;

import org.jdns.jfreechess.chess.ChessPiece;
import org.jdns.jfreechess.ics.IcsMessage;
import org.jdns.jfreechess.ics.IcsMessageHandler;
import org.noos.xing.mydoggy.ContentManager;
import org.noos.xing.mydoggy.ToolWindowAnchor;
import org.noos.xing.mydoggy.ToolWindowManager;

import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class Style12MessageHandler implements IcsMessageHandler {

  private final Map<Integer, JChessBoard> boardMap;

  private final ContentManager contentManager;

  public Style12MessageHandler(ContentManager contentManager) {
    this.contentManager = contentManager;
    this.boardMap = Maps.newLinkedHashMap();
  }

  @Override
  public void messageReceived(IcsMessage message) {
    Iterable<String> content = Splitter.on('\n').split(message.getContent());
    for (String line : content) {
      if (line.startsWith("<12> ")) {
        List<String> fields = Lists.newArrayList(Splitter.on(CharMatcher.WHITESPACE).split(line));
        int gameId = Integer.valueOf(fields.get(16));

        JChessBoard board;

        if (!boardMap.containsKey(gameId)) {
          board = new JChessBoard();
          boardMap.put(gameId, board);

          contentManager.addContent("Game " + gameId, "Game " + gameId, null, board);
        } else {
          board = boardMap.get(gameId);
        }

        for (int i = 1; i <= 8; i++) {
          for (int j = 0; j < 8; j++) {
            ChessPiece piece = parsePiece(fields.get(i).charAt(j));
            board.setPieceAt(j, 8 - i, piece);
          }
        }
        board.repaint();
      }
    }
  }

  private ChessPiece parsePiece(char charAt) {
    if (charAt == '-') {
      return null;
    }

    ChessPiece.Color theColor;

    if (Character.isLowerCase(charAt)) {
      theColor = ChessPiece.Color.WHITE;
    } else {
      theColor = ChessPiece.Color.BLACK;
    }

    ChessPiece.Type theType;
    switch (Character.toLowerCase(charAt)) {
    case 'k':
      theType = ChessPiece.Type.KING;
      break;
    case 'n':
      theType = ChessPiece.Type.KNIGHT;
      break;
    case 'b':
      theType = ChessPiece.Type.BISHOP;
      break;
    case 'q':
      theType = ChessPiece.Type.QUEEN;
      break;
    case 'p':
      theType = ChessPiece.Type.PAWN;
      break;
    case 'r':
      theType = ChessPiece.Type.ROOK;
      break;
    default:
      throw new IllegalArgumentException("Unknown piece type " + charAt);
    }

    return new ChessPiece(theType, theColor);
  }

}
